<?php
/**
 * 电子发票请求接口函数实现类
 *
 * @author xiayuanjun<xiayuanjun@shopex.cn>
 * update 20160620 wangjianjun
 * @version 0.1
 */
class erpapi_invoice_request_invoice extends erpapi_invoice_request_abstract{

    /**
     * 发票创建接口请求
     * @param array $sdf 请求参数
     */
    public function invoice_create($sdf){
        //获取打电子发票接口开蓝票的参数
        $params = kernel::single('invoice_electronic')->getEinvoiceCreateRequestParams($sdf);
        
        //开票发起前 标记开电子发票同步状态为 开蓝票中
        $mdlInOrder = app::get('invoice')->model('order');
        $filter_arr = array("id"=>$sdf["id"]);
        $update_sync_arr = array("sync"=>"1");//标记开蓝票中的状态
        $mdlInOrder->update($update_sync_arr,$filter_arr);
        
        $title = "电子发票开蓝票";
        $callback = array(
                'class'  => get_class($this),
                'method' => 'invoice_create_callback',
                'params' => array(
                    "id" => $sdf["id"],
                    "order_bn" => $sdf["order_bn"],
                    "invoice_time" => $params["invoice_time"],
                    "shop_id" => $sdf["shop_id"],
                    "payee_name" => $sdf["payee_name"],
                    "telephone" => $sdf["telephone"],
                ),
        );
        return $this->__caller->call(EINVOICE_CREATEREQ,$params,$callback,$title,10,$sdf["order_bn"]);
    }
    
    //开蓝票callback函数
    public function invoice_create_callback($response, $callback_params){
        //矩阵调用了 两个接口 alibaba.einvoice.createreq ERP开票请求接口 和 alibaba.einvoice.create.result.get ERP开票结果获取 都会callback回来
        //这里区分是哪个接口返回 step为1是alibaba.einvoice.createreq，step为2是alibaba.einvoice.create.result.get 并获取 $error_msg
        $invoice_result_arr = array(); //默认空数组 为空则说明没有开蓝成功
        if($response["rsp"] == "fail"){
            //只要rsp返回fail不管是step为1还是step为2
            $err_msg = @json_decode($response['err_msg'],true);
            if(is_array($err_msg) && $err_msg["error_response"]["sub_msg"]){
                $return_error_msg = $err_msg["error_response"]["sub_msg"];
            }
        }
        if($response["rsp"] == "succ"){
            //目前ERP开票结果获取接口不管是获取成功create_success或者不成功create_failed rsp都是succ
            $data = @json_decode($response['data'],true);
            if(is_array($data) && $data["step"] == "2" && $data["invoice_result"][0]){
                $invoice_result_arr = $data["invoice_result"][0];
                if($invoice_result_arr["status"] == "create_failed"){
                    $return_error_msg = $invoice_result_arr["biz_error_msg"];
                }
            }
        }
        
        $mdlInOrder = app::get('invoice')->model('order');
        $filter_arr = array("id"=>$callback_params['id']);
        
        //更新 开票状态 is_status 和 电子发票同步状态 sync
        $int_invoice_time = strtotime($callback_params["invoice_time"]);
        $update_arr = array("update_time"=>$int_invoice_time);
        if($invoice_result_arr["status"] == "create_success"){
            //开蓝成功
            $update_arr["dateline"] = $int_invoice_time;
            $update_arr["sync"] = "3";//开蓝成功
            $update_arr["is_status"] = "1";//更新为已开票
            $update_arr["invoice_code"] = $invoice_result_arr["invoice_code"];
            $update_arr["invoice_no"] = $invoice_result_arr["invoice_no"];
            $msg = "电子发票开蓝票成功。";
            //组返回明细数组存明细表中
            $item_update_arr = array(
                    "invoice_code" => $invoice_result_arr["invoice_code"],
                    "invoice_no" => $invoice_result_arr["invoice_no"],
                    "serial_no" => $invoice_result_arr["serial_no"],
                    "create_time" => $int_invoice_time,
            );
            //更新电子发票开票信息明细表 并发送短信
            $mdlInOrderElIt = app::get('invoice')->model('order_electronic_items');
            $filter_item_arr = array("id"=>$callback_params['id'],"billing_type"=>"1");
            $rs_item = $mdlInOrderElIt->update($item_update_arr,$filter_item_arr);
            if($rs_item){
                //电子发票开票成功发送短信提醒
                $mdlOmeShop = app::get('ome')->model('shop');
                $rs_shop = $mdlOmeShop->dump(array("shop_id"=>$callback_params["shop_id"]));
                $sendArr = array(
                        'event_type' => 'einvoice',
                        'order_bn' => $callback_params["order_bn"],
                        'invoice_no' => $invoice_result_arr["invoice_no"],
                        'billing_time' => date("m-d H:i",$int_invoice_time),
                        'payee_name' => $callback_params['payee_name'],
                        'store_name' => $rs_shop["name"],
                        'telephone' => $callback_params["telephone"],
                );
                $sendSms = kernel::single('taoexlib_sms')->sendSms($sendArr, $error_msg);
            }
            //更新订单发票号字段
            $mdlOmeOrders = app::get('ome')->model('orders');
            $update_orders_arr = array("tax_no"=>$invoice_result_arr["invoice_no"]);
            $filter_orders_arr = array("order_bn"=>$callback_params["order_bn"],"shop_id"=>$callback_params["shop_id"]);
            $mdlOmeOrders->update($update_orders_arr,$filter_orders_arr);
        }else{
            //开蓝失败
            $update_arr["sync"] = "2";//开蓝失败
            $update_arr["is_status"] = "0";//保持未开票状态
            $msg = "电子发票开蓝票失败。";
            if($return_error_msg){
                $msg .= "(".$return_error_msg.")";
            }
        }
        //更新发票记录主表
        $mdlInOrder->update($update_arr,$filter_arr);
        
        //记录发票操作日志
        $opObj = app::get('ome')->model('operation_log');
        $opObj->write_log('invoice_billing@invoice', $callback_params['id'], $msg);

        $callback_params['obj_bn']   = $callback_params["order_bn"];
        $callback_params['obj_type'] = "einvoice_blue";//开蓝票
        
        return $this->callback($response, $callback_params);
    }

    /**
     * 发票取消接口请求
     * @param array $sdf 请求参数
     */
    public function invoice_cancel($sdf){
        //获取打电子发票接口开蓝票的参数
        $params = kernel::single('invoice_electronic')->getEinvoiceCreateRequestParams($sdf,"red");
        
        //开票发起前 标记开电子发票同步状态为 开红票中
        $mdlInOrder = app::get('invoice')->model('order');
        $filter_arr = array("id"=>$sdf["id"]);
        $update_sync_arr = array("sync"=>"4");//标记开红票中的状态
        $mdlInOrder->update($update_sync_arr,$filter_arr);
        
        $title = "电子发票冲红";
        $callback = array(
                'class'  => get_class($this),
                'method' => 'invoice_cancel_callback',
                'params' => array(
                        "id" => $sdf["id"],
                        "order_bn" => $sdf["order_bn"],
                        "invoice_time"=>$params["invoice_time"],
                        "shop_id" => $sdf["shop_id"],
                ),
        );
        return $this->__caller->call(EINVOICE_CREATEREQ,$params,$callback,$title,10,$sdf["order_bn"]);
    }
    
    //开蓝票callback函数
    public function invoice_cancel_callback($response, $callback_params){
        //矩阵调用了 两个接口 alibaba.einvoice.createreq ERP开票请求接口 和 alibaba.einvoice.create.result.get ERP开票结果获取 都会callback回来
        //这里区分是哪个接口返回 step为1是alibaba.einvoice.createreq，step为2是alibaba.einvoice.create.result.get 并获取 $error_msg
        $invoice_result_arr = array(); //默认空数组 为空则说明没有冲红成功
        if($response["rsp"] == "fail"){
            //只要rsp返回fail不管是step为1还是step为2
            $err_msg = @json_decode($response['err_msg'],true);
            if(is_array($err_msg) && $err_msg["error_response"]["sub_msg"]){
                $return_error_msg = $err_msg["error_response"]["sub_msg"];
            }
        }
        if($response["rsp"] == "succ"){
            //目前ERP开票结果获取接口不管是获取成功create_success或者不成功create_failed rsp都是succ
            $data = @json_decode($response['data'],true);
            if(is_array($data) && $data["step"] == "2" && $data["invoice_result"][0]){
                $invoice_result_arr = $data["invoice_result"][0];
                if($invoice_result_arr["status"] == "create_failed"){
                    $return_error_msg = $invoice_result_arr["biz_error_msg"];
                }
            }
        }
        
        $mdlInOrder = app::get('invoice')->model('order');
        $filter_arr = array("id"=>$callback_params['id']);
        
        //更新 开票状态 is_status 和 电子发票同步状态 sync
        $int_invoice_time = strtotime($callback_params["invoice_time"]);
        $update_arr = array("update_time"=>$int_invoice_time);
        if($invoice_result_arr["status"] == "create_success"){
            //冲红成功
            $update_arr["sync"] = "6";//冲红成功
            $update_arr["is_status"] = "2";//更新为已作废
            $msg = "电子发票冲红成功。";
            //组返回明细数组存明细表中
            $item_update_arr = array(
                "invoice_code" => $invoice_result_arr["invoice_code"],
                "invoice_no" => $invoice_result_arr["invoice_no"],
                "serial_no" => $invoice_result_arr["serial_no"],
                "create_time" => $int_invoice_time,
            );
            //更新电子发票开票信息明细表
            $mdlInOrderElIt = app::get('invoice')->model('order_electronic_items');
            $filter_item_arr = array("id"=>$callback_params['id'],"billing_type"=>"2");
            $mdlInOrderElIt->update($item_update_arr,$filter_item_arr);
            //更新订单发票号字段
            $mdlOmeOrders = app::get('ome')->model('orders');
            $update_orders_arr = array("tax_no"=>$invoice_result_arr["invoice_no"]);
            $filter_orders_arr = array("order_bn"=>$callback_params["order_bn"],"shop_id"=>$callback_params["shop_id"]);
            $mdlOmeOrders->update($update_orders_arr,$filter_orders_arr);
        }else{
            //冲红失败
            $update_arr["sync"] = "5";//冲红失败
            $update_arr["is_status"] = "1";//保持已开票状态
            $msg = "电子发票冲红失败。";
            if($return_error_msg){
                $msg .= "(".$return_error_msg.")";
            }
        }
        //更新发票记录主表
        $mdlInOrder->update($update_arr,$filter_arr);
        
        //记录发票操作日志
        $opObj = app::get('ome')->model('operation_log');
        $opObj->write_log('invoice_billing@invoice', $callback_params['id'], $msg);
        
        $callback_params['obj_bn']   = $callback_params["order_bn"];
        $callback_params['obj_type'] = "einvoice_red";//开红票
    
        return $this->callback($response, $callback_params);
    }
    
    /**
     * 电子发票获取url
     * @param array $sdf 请求参数
     */
    public function invoice_get_url($sdf){
        //组打接口获取电子发票url的参数
        $params = kernel::single('invoice_electronic')->getEinvoiceGetUrlRequestParams($sdf);
        $title = "获取电子发票url地址";
        return $this->__caller->call(EINVOICE_URL_GET,$params,null,$title,10,$sdf["order_bn"]);
    }
    
    /**
     * 查询已回传淘宝的电子发票
     * @param array $sdf 请求参数
     */
    public function invoice_get_info($sdf){
        //组接口参数
        $params = array("tid"=>$sdf["order_bn"]);
        $title = "查询已回传淘宝的电子发票";
        return $this->__caller->call(EINVOICE_INVOICE_GET,$params,null,$title,10,$sdf["order_bn"]);
    }
    
    /**
     * 回流天猫前 电子发票状态更新
     * @param array $sdf 请求参数
     */
    public function invoice_einvoice_prepare($sdf){
        $invoice_type = 1;//默认蓝票
        if($sdf["einvoice_type"] == "red"){
            //已作废并且冲红成功
            $invoice_type = 2;//红票
        }
        //组接口参数
        $params = array(
            "tid" => $sdf["order_bn"],
            "invoice_action_type" => $sdf["invoice_action_type"],
            "invoice_type" => $invoice_type,
            "serial_no" => $sdf["serial_no"],
            "invoice_title" => $sdf["title"]?$sdf["title"]:$sdf["tax_company"],
        );
        $title = "天猫电子发票状态更新";
        return $this->__caller->call(EINVOICE_INVOICE_PREPARE,$params,null,$title,10,$sdf["order_bn"]);
    }
    
    /**
     * 电子发票回流天猫
     * @param array $sdf 请求参数
     */
    public function invoice_upload_tmall($sdf){
        //组打接口电子发票回流天猫的参数
        $params = kernel::single('invoice_electronic')->getEinvoiceUploadTmallRequestParams($sdf);
        $title = "电子发票回流天猫";
        return $this->__caller->call(EINVOICE_DETAIL_UPLOAD,$params,null,$title,25,$sdf["order_bn"]);
    }

    /**
     * 电子发票开票(蓝票或者红票)后获取发票开票结果查询
     * @param array $sdf 请求参数
     */
    public function invoice_create_result($sdf){
        //组打接口获取发票开票结果的参数
        $params = kernel::single('invoice_electronic')->getEinvoiceCreateResultParams($sdf);
        $title = "获取发票开票结果";
        return $this->__caller->call(EINVOICE_CREATE_RESULT_GET,$params,null,$title,10,$sdf["order_bn"]);
    }
    
}